﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
/// <summary>
/// Author: toanvt
/// CreatedDate: 12/12/2011
/// Description: Danh sách sản phẩm
/// </summary>
public partial class Administrator_AdminProducts : System.Web.UI.Page
{
    private Int32 danhMucID=-1;
    private Int32 pageIndex = 1;
    private Int32 pageSize = 10;
    private Int32 totalRecord;
    private DataTable dtDanhMucSanPham = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            pageIndex = Int32.Parse(Request.QueryString["PageIndex"].ToString());
        }
        catch (Exception)
        {
            pageIndex = 1;
        }

        try
        {
            danhMucID = Int32.Parse(Request.QueryString["DanhMucID"].ToString());
        }
        catch (Exception)
        {
            danhMucID = -1;
        }
        if (!Page.IsPostBack)
        {
            Int32 totalRecord = 0;
            dtDanhMucSanPham = DanhMucSanPhamProvider.GetDanhMucSanPhamsForBackEnd(-1, pageIndex, pageSize, out totalRecord).Tables[0];
            LoadSanPhams(danhMucID);
            CreateTreeViewCategory();
        }
    }
   
    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: Lấy dữ liệu sản phẩm theo mã sản phẩm
    /// </summary>
    /// <param name="DanhMucID">Mã sản phẩm</param>
    /// 
    private void CreateTreeViewCategory()
    {
        TreeNode level0 = new TreeNode("Danh mục Sản phẩm", "-1");
        CreateTreeViewCategorys(level0,-1);
        tvCategorys.Nodes.Add(level0);

        ExpandPathOfTreeNode(this.tvCategorys.SelectedNode);
    }
    /// <summary>
    /// Author:tungvu90
    /// CreateDate:06/02/2012
    /// Description:Phương thức đệ quy taok TreeView
    /// </summary>
    /// <param name="treeNode"></param>
    /// <param name="chuyenMucChaID"></param>
    private void CreateTreeViewCategorys(TreeNode treeNode, Int32 chuyenMucChaID)
    {
        DataRow[] dataRowsSubCategorys = dtDanhMucSanPham.Select("ChuyenMucChaID="+chuyenMucChaID.ToString());
        Int32 amountOfSubCategory = dataRowsSubCategorys.Count();

        //Điểm dừng đệ quy
        if (amountOfSubCategory == 0)
            return;

        TreeNode tn;

        for (Int32 i = 0; i < amountOfSubCategory; ++i)
        {
            Int32 subCategoryID = Int32.Parse(dataRowsSubCategorys[i]["DanhMucID"].ToString());
            tn = new TreeNode(dataRowsSubCategorys[i]["TenDanhMucVN"].ToString(),subCategoryID.ToString());
            tn.CollapseAll();
            CreateTreeViewCategorys(tn, subCategoryID);

            if (subCategoryID == danhMucID)
            {
                tn.Select();
            }

            treeNode.ChildNodes.Add(tn);
            tn = null;
        }
    }

    /// <summary>
    /// Author : toanvt
    /// CreatedDate : 10/02/2012
    /// Description : Expand Path of TreeNode
    /// </summary>
    /// <param name="tn"></param>
    private void ExpandPathOfTreeNode(TreeNode tn)
    {
        TreeNode tmpTreeNode = tn;

        if (tn == null)
            return;

        do
        {
            tmpTreeNode.Expand();
            TreeNode tmp = tmpTreeNode;
            tmpTreeNode = null;
            tmpTreeNode = tmp.Parent;
        }
        while (tmpTreeNode != null);
    }

    private void LoadSanPhams(Int32 danhMucID)
    {
        EHTWebsite.Code.SanPham theSanPham = new EHTWebsite.Code.SanPham();
        theSanPham.TenSanPhamVN = "";
        theSanPham.TenSanPhamOther = "";
        theSanPham.DanhMucID = danhMucID;
        theSanPham.NoiBat = false;
        DataSet dsSanPham = SanPhamProvider.GetSanPhamsForBackEnd(theSanPham, pageIndex, pageSize, out totalRecord);
        if (dsSanPham.Tables[0].Rows.Count > 0)
        {
            rpSanPham.DataSource = dsSanPham;
            rpSanPham.DataBind();
            foreach (RepeaterItem item in rpSanPham.Items)
            {
                CheckBox ckPublish = (CheckBox)item.FindControl("ckPublish");
                if (ckPublish.Checked == true)
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/btncheck.png";
                }
                else
                {
                    ((ImageButton)item.FindControl("btnPublish")).ImageUrl = "Templates/Images/unpublish.jpg";
                }
            }
        }

        // thêm vào cho phân trang
        PaggingControl1.PageURL = "AdminProducts.aspx?DanhMucID=" +danhMucID.ToString();
        PaggingControl1.PageIndex = pageIndex;
        PaggingControl1.TotalRecord = totalRecord;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Administrator/AdminProductIU.aspx?danhMucID=" + danhMucID);
    }

    protected void rpDanhMucSanPham_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        String cmdName = e.CommandName;
        Int32 SanPhamID = -1;

        try
        {
            SanPhamID = Int32.Parse(e.CommandArgument.ToString());
        }
        catch (Exception ex)
        {
        }

        if (cmdName.ToLower() == "delete1")
        {
            SanPhamProvider.DeleteSanPhamBySanPhamID(SanPhamID);
            LoadSanPhams(-1);
        }
        else if (cmdName == "change_number_of_order")
        {
            try
            {
                Int32 sapxep = Int32.Parse(((TextBox)e.Item.FindControl("txtNumberOfOrder")).Text.Trim());
                SanPhamProvider.UpdateNumberOfOrderBySanPhamId(SanPhamID, sapxep);
            }
            catch (Exception ex)
            {
              
            }
            LoadSanPhams(danhMucID);
        }
        else if (cmdName == "publish")
        {
            SanPhamProvider.ChangePublishBySanPhamID(SanPhamID);
            LoadSanPhams(danhMucID);
        }
        else if (cmdName == "save_all")
        {
            foreach (RepeaterItem item in rpSanPham.Items)
            {

                Int32 sapxep = Int32.Parse(((TextBox)item.FindControl("txtNumberOfOrder")).Text.Trim());
                SanPhamID = Int32.Parse(((Literal)item.FindControl("ltrSanPhamID")).Text.Trim());
                SanPhamProvider.UpdateNumberOfOrderBySanPhamId(SanPhamID,sapxep);
            }

            LoadSanPhams(danhMucID);
        }
    }
    
    /// <summary>
    /// Author: toanvt
    /// CreatedDate: 12/12/2011
    /// Description: Kiểm tra file tồn tại trên server
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private bool RemoteFileExists(string url)
    {
        bool result = false;

        using (System.Net.WebClient client = new WebClient())
        {
            try
            {
                Stream stream = client.OpenRead(url);
                if (stream != null)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch
            {
                result = false;
            }
        }
        return result;
    }

    protected void rpSanPham_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Image imgHinhAnh = (Image)e.Item.FindControl("imgHinhAnhUrl");
        Label lbHinhAnh = (Label)e.Item.FindControl("lbHinhAnhUrl");

        if (lbHinhAnh != null)
        {
            if (string.IsNullOrEmpty(lbHinhAnh.Text) == false)
            {
                if ((RemoteFileExists(@"~\ImageDatas\Products\" + lbHinhAnh.Text)) == false)
                {
                    imgHinhAnh.ImageUrl = @"~\ImageDatas\Products\" + lbHinhAnh.Text;
                }
                else
                {
                    imgHinhAnh.ImageUrl = @"~\ImageDatas\Products\noImage.gif";
                }
            }
            else
            {
                imgHinhAnh.ImageUrl = @"~\ImageDatas\Products\noImage.gif";
            }
        }
    }

    protected void tvCategorys_SelectedNodeChanged(object sender, EventArgs e)
    {
        Response.Redirect("AdminProducts.aspx?DanhMucID=" +this.tvCategorys.SelectedNode.Value);
    }
}
